package live.hotel.dao.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import live.common.DBHelper;
import live.common.Format;
import live.common.Page;
import live.hotel.dao.IXmlManage;
import live.hotel.entity.*;

import org.dom4j.Document;
import org.dom4j.Element;


public class OrderMange {
	private Document doc = null;
	private IXmlManage xmlMan = new XmlManage();
	private StringBuffer orderBuf = null;
	
	/**
	 * 返回订单号
	 * 
	 * @param item
	 * @return
	 * @throws Exception
	 */
	public Order returnOrder(Order item) throws Exception {
		//doc = getOrderReponse(item);
		String orderId = null;
	/*	if (doc != null) {
			try{
			orderId = doc.selectSingleNode("//OrderId").getText();
			item.setOrderId(orderId);
			item.setTotalSalePrice(doc.selectSingleNode("//TotalSalePrice")
					.getText());
			item.setTotalBalsPrice(doc.selectSingleNode("//TotalBalsPrice")
					.getText());
			item.setTotalCommision(doc.selectSingleNode("//TotalCommision")
					.getText());
			item.setOtherRemark(doc.selectSingleNode("//OtherRemark")
							.getText());
				
			}catch(Exception e){
				e.printStackTrace();
			}
			// item.setTotalCommision(returnCommisionTotal(doc,
			// "//RoomQuatations/*"));
			 
		}*/
		addOrder(item);
		return item;
	}
	
	/**
	 * 佣金总价
	 * @param doc
	 * @param nodeName
	 * @return
	 */
	private String returnCommisionTotal(Document doc, String nodeName) {
		List<String> nodes = doc.selectNodes(nodeName);
		Iterator iterator = nodes.iterator();
		double commisionTotal = 0D;
		Element element = null;
		while (iterator.hasNext()) {
			element = (Element) iterator.next();
			commisionTotal += Double.parseDouble(element
					.elementTextTrim("Commision"));
		}
		return commisionTotal + "";
	}
	
	/**
	 * 新增订单
	 * @param item
	 * @throws SQLException
	 */
	private void addOrder(Order item) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		String otherInfos = item.getOtherRemark();
		db
				.update(new StringBuffer("INSERT INTO Hotel_Order (orderNo,inDate,outDate,memberNum,placeTime,totalSalePrice,totalBalsPrice,totalCommision,roomType,hotelName,webOrder,roomNum) ")
						.append(" VALUES ('").append(item.getOrderId()).append("','")
						.append(item.getCheckInDate()).append("','").append(item.getCheckOutDate())
						.append("','").append(otherInfos!=null?otherInfos:"")
						.append("','").append(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()))
						.append("',").append(item.getTotalSalePrice()).append(",").append(item.getTotalBalsPrice())
						.append(",").append(item.getTotalCommision()).append(",'").append(item.getRoomType())
						.append("','").append(item.getHotelName()).append("','").append(item.getWebOrder())
						.append("',").append(item.getNumberOfRooms() + ")").toString());
		db.close();
	}

	/**
	 * 查询订单
	 * @param storeNo
	 * @return
	 * @throws SQLException
	 */
	public List<Order> queryOrders(String storeNo) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		Order item = null;
		List results = new ArrayList();
		List<Map> orderList = db
				.queryRecordsMap("SELECT * FROM Hotel_Order where storeNo='"
						+ storeNo + "' order by placeTime desc");
		for (Map map : orderList) {
			item = new Order();
			item.setOrderId(map.get("orderNo").toString());
			item.setTotalSalePrice(map.get("totalSalePrice").toString());
			item.setCheckInDate(map.get("placeTime").toString());
			item.setOrderStatus(map.get("status").toString());
			item.setName(map.get("memberNum").toString());
			results.add(item);
		}
		db.close();
		return results;
	}

	/****
	 * 查询分页
	 * @throws SQLException 
	 */

	@SuppressWarnings("unchecked")
	public List<Order> queryOrders_fy(String storeNo, Page page) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		Order item = null;
		List results = new ArrayList();
		String execSql = "SELECT * FROM Hotel_Order WHERE 1=1 AND storeNo='"+storeNo+"' order by placeTime desc ";
		String sql = "{call pro_Common_PageView(?,?,?,?)}";
		Object[] args = new Object[4];
		args[0]=execSql;
		args[1]=page.getPageIndex();
		args[2]=page.getPageSize();
		args[3]="";
		List<Map> orderList = db.queryRecordsMap(sql,args);
		for (Map map : orderList) {
			item = new Order();
			item.setOrderId(map.get("orderNo").toString());
			item.setTotalSalePrice(map.get("totalSalePrice").toString());
			item.setCheckInDate(map.get("placeTime").toString());
			item.setOrderStatus(map.get("status").toString());
			item.setName(map.get("memberNum").toString());
			item.setHotelName(map.get("hotelName").toString());
			item.setRoomType(map.get("roomType").toString());
			item.setNumberOfRooms(Integer.valueOf(map.get("roomNum").toString()));
			results.add(item);
		}
		db.close();
		return results;
	}
	
	public List queryOrders(Page page) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		String execSql = "{call pro_Common_PageView(?,?,?,?)}";
		StringBuffer sql=new StringBuffer("SELECT * FROM Hotel_Order order by placeTime desc");
		Object[] args = new Object[4];
		args[0]=sql.toString();	args[1]=page.getPageIndex();	
		args[2]=page.getPageSize();	args[3]="";
		List<Order> orders = null;
		List<Map> list = db.queryRecordsMap(execSql,args);
		if (Format.getInstance().isNotNullOrZeroForList(list)) {
			Order order = null;
			orders = new ArrayList<Order>();
			for (Map map : list) {
				order = returnOrderInfo(map);
				orders.add(order);
			}
		}
		page.setRecordCount(db.returnOutParam(execSql, args));
		db.close();
		return orders;
	}
	
	@SuppressWarnings("unchecked")
	public int mobbile_sum(String storeNo) throws SQLException {
		DBHelper db = DBHelper.getInstance();
		StringBuffer sql = new StringBuffer(
				"select count(*) as sumcount FROM Hotel_Order  where  storeNo='"
						+ storeNo + "'");
		List<Map> lsitmap = db.queryRecordsMap(sql.toString());
		db.close();
		for (Map map : lsitmap) {
			return Integer.valueOf(map.get("sumcount").toString());
		}
		return 0;
	}

	/**
	 * 查询订单信息
	 * 
	 * @param orderId
	 * @return
	 * @throws Exception
	 */
	public Order getOrderByOrderId(String orderId) throws Exception {
		orderBuf = new StringBuffer("<SearchBookingItemRequest>\n").append(
				"<OrderId>").append(orderId).append("</OrderId>\n").append(
				"</SearchBookingItemRequest>\n").append("</RequestDetails>\n")
				.append("</Request>\n");
		doc = xmlMan.getDataFromApi(orderBuf.toString());
		Order order = null;
		if (doc != null) {
			order = new Order();
			order.setOrderId(returnXmlNodeText(doc, "//OrderId"));
			order.setPayType(returnXmlNodeText(doc, "//PaymentMethod"));
			order.setOrderStatus(returnXmlNodeText(doc, "//OrderStatus"));
			// order.setCity(((Element)doc.selectSingleNode("//City")).attributeValue("Code"));
			order.setCityText(returnXmlNodeText(doc, "//City"));
			order.setItemText(returnXmlNodeText(doc, "//Item"));
			order.setRoomType(returnXmlNodeText(doc, "//Room"));
			order.setHotelAddress(returnXmlNodeText(doc, "//HotelAddress"));
			order.setCreateTime(returnXmlNodeText(doc, "//CreationTime"));
			order.setCancellTime(returnXmlNodeText(doc, "//CancellationTime"));
			order.setCheckInDate(returnXmlNodeText(doc, "//CheckInDate"));
			order.setCheckOutDate(returnXmlNodeText(doc, "//CheckOutDate"));
			order.setName(returnXmlNodeText(doc, "//Name"));
			order.setRoomNo(returnXmlNodeText(doc, "//RoomNo"));
			order.setInvoiceTax(returnXmlNodeText(doc, "//InvoiceTax"));
		}
		return order;
	}

	public String returnXmlNodeText(Document doc, String xpath) {
		return doc.selectSingleNode(xpath).getText();
	}

	public List<Order> getOrders(Order item, Page page) throws Exception {
		orderBuf = new StringBuffer("<SearchBookingRequest>\n").append(
				"<Pager IsPager=\"true\">\n").append(
				"<PageIndex>" + page.getPageIndex() + "</PageIndex>\n").append(
				"<PageSize>" + page.getPageSize() + "</PageSize>\n").append(
				"</Pager>\n").append("<OrderId></OrderId>\n").append(
				"<BookingDateRange DateType=\""
						+ (item.getDateType() != null ? item.getDateType()
								: "Creation") + "\">\n")
				.append(
						"<FromDate>"
								+ (item.getFormDate() != null ? item
										.getFormDate() : "") + "</FromDate>\n")
				.append(
						"<ToDate>"
								+ (item.getToDate() != null ? item.getToDate()
										: "") + "</ToDate>\n").append(
						"</BookingDateRange>\n").append(
						" <BookingStatusCode>"
								+ (item.getBookingStatusCode() != null ? item
										.getBookingStatusCode() : "")
								+ "</BookingStatusCode>\n").append(
						" <CheckInStatusCode>"
								+ (item.getCheckInStatusCode() != null ? item
										.getCheckInStatusCode() : "")
								+ "</CheckInStatusCode>\n").append(
						"</SearchBookingRequest>\n").append(
						"</RequestDetails>\n").append("</Request>");
		xmlMan.getDataFromApi(orderBuf.toString());
		return null;
	}

	/**
	 * 获取服务端返回的数据信息
	 * 
	 * @param item
	 * @return
	 * @throws Exception
	 */
	public Document getOrderReponse(Order item) throws Exception {
		orderBuf = new StringBuffer("<AddBookingRequest>\n<CheckInPaxItem>\n")
				.append("<Nationality>").append(
						item.getNationality() != null ? item.getNationality()
								: "").append("</Nationality>\n").append(
						"<PaxNames>\n");
		for (String pax : item.getPaxInfos()) {
			orderBuf.append("<PaxName Type=\"D\">").append(pax).append(
					"</PaxName>\n");
		}
		orderBuf
				// .append("<PaxName Type=\"F\">MAX</PaxName>\n")
				.append("</PaxNames>\n").append("<Mobile>").append(
						item.getMobile() != null ? item.getMobile() : "")
				.append("</Mobile>\n").append("<Tel>").append(
						item.getTel() != null ? item.getTel() : "").append(
						"</Tel>\n").append("</CheckInPaxItem>\n").append(
						"<ArrivalTime From=\"").append(
						item.getArrivalTimeFrom() != null ? item
								.getArrivalTimeFrom() : "").append("\" To=\"")
				.append(
						item.getArrivalTimeTo() != null ? item
								.getArrivalTimeTo() : "").append("\"/>")
				.append("<BookingItem>\n").append("<City Code=\"").append(
						item.getCity() != null ? item.getCity() : "").append(
						"\"/>\n").append("<Item Code=\"").append(
						item.getItem() != null ? item.getItem() : "").append(
						"\"/>\n").append("<Room Code=\"").append(
						item.getRoomType() != null ? item.getRoomType() : "")
				.append("\" NumberOfRooms=\"").append(
						item.getNumberOfRooms() != 0 ? item.getNumberOfRooms()
								: 1).append("\" NumberOfDb=\"0\"/>\n").append(
						"<PeriodOfStay>\n").append("<CheckInDate>").append(
						item.getCheckInDate() != null ? item.getCheckInDate()
								: "").append("</CheckInDate>\n").append(
						"<CheckOutDate>").append(
						item.getCheckOutDate() != null ? item.getCheckOutDate()
								: "").append("</CheckOutDate>\n").append(
						"</PeriodOfStay>\n").append("</BookingItem>\n").append(
						"<ContactPaxItem>\n").append("<ConfirmMethods>\n");
		if (item.getMobile() != null && !item.getMobile().trim().equals("")) {
			orderBuf.append("<ConfirmMethod>SMS</ConfirmMethod>");
		}
		if (item.getTele() != null && !item.getTele().trim().equals("")) {
			orderBuf.append("<ConfirmMethod>TELE</ConfirmMethod>");
		}
		if (item.getManualfax() != null
				&& !item.getManualfax().trim().equals("")) {
			orderBuf.append("<ConfirmMethod>MANUALFAX</ConfirmMethod>");
		}
		if (item.getEmail() != null && !item.getEmail().trim().equals("")) {
			orderBuf.append("<ConfirmMethod>EMAIL</ConfirmMethod>");
		}
		orderBuf.append("</ConfirmMethods>\n").append("<Name>").append(
				item.getName() != null ? item.getName() : "").append(
				"</Name>\n").append("<Tel>").append(
				item.getTele() != null ? item.getTele() : "")
				.append("</Tel>\n").append("<Mobile>").append(
						item.getMobile() != null ? item.getMobile() : "")
				.append("</Mobile>\n").append("<Fax>").append(
						item.getManualfax() != null ? item.getManualfax() : "")
				.append("</Fax>\n").append("<Email>").append(
						item.getEmail() != null ? item.getEmail() : "").append(
						"</Email>\n").append("</ContactPaxItem>\n").append(
						"<OtherRemark>").append(
						item.getOtherRemark() != null ? item.getOtherRemark()
								: "").append("</OtherRemark>").append(
						"</AddBookingRequest>\n").append(
						"</RequestDetails>\n</Request>");
		return xmlMan.getDataFromApi(orderBuf.toString());
	}

	private Order returnOrderInfo(Map map) {
		Order order = null;
		if (Format.getInstance().isNotNullOrZeroForMap(map)) {
			order = new Order();
			order.setOrderId(map.get("orderNo").toString());
			order.setCheckInDate(map.get("inDate").toString());
			order.setCheckOutDate(map.get("outDate").toString());
			order.setHotelName(map.get("hotelname")!=null?map.get("hotelname").toString():null);
			order.setNumberOfRooms(map.get("payType")!=null?Integer.parseInt(map.get("payType")
					.toString()):0);
			order.setTotalSalePrice(map.get("totalsaleprice").toString());
			order.setRoomType(map.get("roomType")!=null?map.get("roomType").toString():null);
			order.setWebOrder(map.get("webOrder")!=null?map.get("webOrder").toString():null);
		}
		return order;
	}

	public String revokeOrder(Order Item) {
		return null;
	}
}
